import { ref, computed, h, watch } from 'vue'
import { nanoid } from 'nanoid'
import { message } from 'ant-design-vue'
import { renderExportForm } from '@/render/ReviewRender'
import { renderHSTable } from '@/render/HSRender'
import {
  getReviewData,
  getHscode,
  getBusinessKnowledge,
  getBusinessKnowledgeStream,
} from '@/api/api'
import MarkdownIt from 'markdown-it'
// 移除 XStream 导入，自己实现流式处理
const md = new MarkdownIt()

// 获取AI结果
const getRenderContent = async (nextContent, files, scene, config = {}) => {
  switch (scene) {
    case '业务知识':
      // 业务知识使用流式输出，直接返回流式数据
      const readableStream = await getBusinessKnowledgeStream(nextContent, config)
      return { isStream: true, readableStream }
    case '制单审核':
      const res_review = await getReviewData(
        {
          query: nextContent,
        },
        config,
      ) // 传入配置，包含 signal
      console.log('🐯 ~ getRenderContent ~ res:', res_review)
      return renderExportForm(res_review.data, res_review.pdf_url, res_review.pdf_size)
    case '申报要素':
      const res_hscode = await getHscode(
        {
          query: nextContent,
        },
        config,
      ) // 传入配置，包含 signal
      console.log('🐯 ~ getRenderContent ~ res:', res_hscode)
      return renderHSTable(res_hscode.data)

    default:
      return '该功能模块正在开发中...'
  }
}

export function useMessages(activeKey) {
  // 使用 Map 存储每个会话的消息
  const messagesMap = ref(new Map())
  const tempMessages = ref([])
  const content = ref('')
  const requestLoading = ref(false)
  let aiAbortController = null

  // 获取当前会话的消息
  const getCurrentMessages = (key) => {
    if (!messagesMap.value.has(key)) {
      messagesMap.value.set(key, [])
    }
    return messagesMap.value.get(key)
  }

  const BubbleItems = computed(() => {
    if (activeKey.value === null) {
      // 新对话状态，显示临时消息
      return tempMessages.value.map(formatMessage)
    } else {
      // 已有对话，显示对应消息
      const currentMessages = getCurrentMessages(activeKey.value)
      return currentMessages.map(formatMessage)
    }
  })

  watch(activeKey, (newVal, oldVal) => {
    console.log('🐯 ~ watch ~ oldVal,newVal:', oldVal, newVal)
    if (!newVal) {
    }
  })

  // const formatMessage = ({ id, message, role, loading }) => {
  //   const base = {
  //     key: id,
  //     role,
  //     loading,
  //     // footer:
  //   }

  //   if (role === 'ai') {
  //     if (typeof message === 'string') {
  //       // base.typing = { step: 2, interval: 50 }
  //       base.content = message
  //       base.onTypingComplete = () => {}
  //     } else {
  //       base.messageRender = () => h(message)
  //     }
  //   } else {
  //     base.content = message
  //   }

  //   return base
  // }

  const formatMessage = ({ id, message, role, loading }) => {
    const base = {
      key: id,
      role,
      loading,
    }

    if (role === 'ai') {
      // 直接传递消息内容，让 chat.js 中的 messageRender 处理渲染
      base.content = message
    } else {
      base.content = message
    }

    return base
  }

  const sendMessage = async (
    { content: nextContent, files, scene },
    isCreatingNewConversation,
    conversationsItems,
  ) => {
    if (!nextContent && (!files || !files.length)) return
    requestLoading.value = true
    console.log(nextContent, files, scene)
    // 第一次发送消息或在新建对话状态
    if (isCreatingNewConversation.value) {
      // 如果有文件，添加文件消息
      if (files && files.length > 0) {
        tempMessages.value.push({
          id: nanoid(),
          role: 'file',
          message: files,
        })
      }

      // 添加用户消息到临时区
      tempMessages.value.push({
        id: nanoid(),
        message: nextContent,
        role: 'local',
        loading: false,
      })

      // 添加 AI loading 消息
      const aiId = nanoid()
      tempMessages.value.push({
        id: aiId,
        message: '',
        role: 'ai',
        loading: true,
        scene: scene, // 添加场景信息
      })

      // 创建新的 AbortController
      aiAbortController = new AbortController()

      try {
        // await new Promise((resolve) => setTimeout(resolve, 1000))
        const aiReply = await getRenderContent(nextContent, files, scene, {
          signal: aiAbortController.signal, // 传入 signal
        })

        // 处理流式输出
        if (aiReply.isStream && scene === '业务知识') {
          let streamContent = ''

          // 直接处理ReadableStream
          const reader = aiReply.readableStream.getReader()
          const decoder = new TextDecoder()

          try {
            while (true) {
              const { done, value } = await reader.read()
              if (done) break

              // 解码数据
              const chunk = decoder.decode(value, { stream: true })
              console.log('收到流式数据块:', chunk)

              // 按行分割处理
              const lines = chunk.split('\n')
              for (const line of lines) {
                if (line.trim() === '') continue

                try {
                  // 解析SSE格式的数据
                  if (line.startsWith('data: ')) {
                    const raw = line.slice(6) // 移除 'data: ' 前缀
                    console.log('解析到数据:', raw)

                    // 解析形如 {"text":"..."} 的数据
                    let dataText = raw
                    try {
                      const obj = JSON.parse(raw)
                      if (obj && typeof obj === 'object' && typeof obj.text === 'string') {
                        dataText = obj.text
                      }
                    } catch (_) {
                      // 非 JSON 字符串，按原样处理
                    }

                    // 过滤掉<think>和</think>标签以及[DONE]标记
                    if (
                      dataText.includes('<think>') ||
                      dataText.includes('</think>') ||
                      dataText.includes('[DONE]')
                    ) {
                      console.log('🐯 ~ 跳过数据块:', dataText)
                      continue // 跳过这些内容
                    }

                    streamContent += dataText
                    console.log('🐯 ~ 添加内容:', dataText, '当前总内容:', streamContent)

                    // 实时更新AI消息内容
                    const idx = tempMessages.value.findIndex((m) => m.id === aiId)
                    if (idx !== -1) {
                      tempMessages.value[idx] = {
                        ...tempMessages.value[idx],
                        message: streamContent,
                        loading: false, // 流式输出过程中保持loading状态
                        scene: scene,
                      }
                      console.log('🐯 ~ 更新消息:', tempMessages.value[idx])
                    }
                  }
                } catch (parseError) {
                  console.error('解析流式数据失败:', parseError)
                }
              }
            }
          } finally {
            reader.releaseLock()
          }

          // 流式输出完成，更新最终状态
          const idx = tempMessages.value.findIndex((m) => m.id === aiId)
          if (idx !== -1) {
            tempMessages.value[idx] = {
              ...tempMessages.value[idx],
              message: streamContent,
              loading: false,
              scene: scene,
            }
          }
        } else {
          // 非流式输出，按原逻辑处理
          const idx = tempMessages.value.findIndex((m) => m.id === aiId)
          if (idx !== -1) {
            tempMessages.value[idx] = {
              ...tempMessages.value[idx],
              message: aiReply,
              loading: false,
              scene: scene, // 保持场景信息
            }
          }
        }

        // AI 回复后，创建新会话
        const newKey = nanoid()
        // 使用用户第一句话作为会话标题
        const newLabel = nextContent.trim().slice(0, 10) || '新聊天'
        conversationsItems.value.push({
          key: newKey,
          label: newLabel,
        })

        // 将临时消息转移到新会话
        messagesMap.value.set(newKey, [...tempMessages.value])

        // 激活新会话
        activeKey.value = newKey

        // 清空临时消息与输入框
        tempMessages.value = []
        content.value = ''
      } catch (e) {
        console.log('🐯 ~ useMessages ~ e:', e)
        // 错误处理
        const idx = tempMessages.value.findIndex((m) => m.id === aiId)
        if (idx !== -1) {
          // 判断是否是取消请求导致的错误
          const message = e.name === 'CanceledError' ? '您已取消请求。' : 'AI请求失败，请重试'
          tempMessages.value[idx] = {
            ...tempMessages.value[idx],
            message,
            loading: false,
            scene: scene, // 保持场景信息
          }
        }
        if (e.name !== 'CanceledError') {
          message.error('AI请求失败')
        }
      } finally {
        requestLoading.value = false
        aiAbortController = null
      }
    } else {
      // 现有会话流程
      const currentMessages = getCurrentMessages(activeKey.value)

      // 如果有文件，添加文件消息
      if (files && files.length > 0) {
        currentMessages.push({
          id: nanoid(),
          role: 'file',
          message: files,
        })
      }

      // 添加用户消息
      const userMessage = {
        id: nanoid(),
        message: nextContent,
        role: 'local',
        loading: false,
      }
      currentMessages.push(userMessage)

      // 添加 AI 消息
      const aiId = nanoid()
      const aiMessage = {
        id: aiId,
        message: '',
        role: 'ai',
        loading: true,
        scene: scene, // 添加场景信息
      }
      currentMessages.push(aiMessage)

      // 创建新的 AbortController
      aiAbortController = new AbortController()

      try {
        // await new Promise((resolve, reject) => setTimeout(resolve, 1000))
        const aiReply = await getRenderContent(nextContent, files, scene, {
          signal: aiAbortController.signal, // 传入 signal
        })

        // 处理流式输出
        if (aiReply.isStream && scene === '业务知识') {
          let streamContent = ''

          // 直接处理ReadableStream
          const reader = aiReply.readableStream.getReader()
          const decoder = new TextDecoder()

          try {
            while (true) {
              const { done, value } = await reader.read()
              if (done) break

              // 解码数据
              const chunk = decoder.decode(value, { stream: true })
              console.log('收到流式数据块:', chunk)

              // 按行分割处理
              const lines = chunk.split('\n')
              for (const line of lines) {
                if (line.trim() === '') continue

                try {
                  // 解析SSE格式的数据
                  if (line.startsWith('data: ')) {
                    const raw = line.slice(6) // 移除 'data: ' 前缀
                    console.log('解析到数据:', raw)

                    // 解析形如 {"text":"..."} 的数据
                    let dataText = raw
                    try {
                      const obj = JSON.parse(raw)
                      if (obj && typeof obj === 'object' && typeof obj.text === 'string') {
                        dataText = obj.text
                      }
                    } catch (_) {
                      // 非 JSON 字符串，按原样处理
                    }

                    // 过滤掉<think>和</think>标签以及[DONE]标记
                    if (
                      dataText.includes('<think>') ||
                      dataText.includes('</think>') ||
                      dataText.includes('[DONE]')
                    ) {
                      console.log('🐯 ~ 跳过数据块:', dataText)
                      continue // 跳过这些内容
                    }

                    streamContent += dataText
                    console.log('🐯 ~ 添加内容:', dataText, '当前总内容:', streamContent)

                    // 实时更新AI消息内容
                    const idx = currentMessages.findIndex((m) => m.id === aiId)
                    if (idx !== -1) {
                      currentMessages[idx] = {
                        ...currentMessages[idx],
                        message: streamContent,
                        loading: false, // 流式输出过程中保持loading状态
                        scene: scene,
                      }

                      // 更新 Map 中的消息列表
                      messagesMap.value.set(activeKey.value, currentMessages)
                      console.log('🐯 ~ 更新消息:', currentMessages[idx])
                    }
                  }
                } catch (parseError) {
                  console.error('解析流式数据失败:', parseError)
                }
              }
            }
          } finally {
            reader.releaseLock()
          }

          // 流式输出完成，更新最终状态
          const idx = currentMessages.findIndex((m) => m.id === aiId)
          if (idx !== -1) {
            currentMessages[idx] = {
              ...currentMessages[idx],
              message: streamContent,
              loading: false,
              scene: scene,
            }

            // 更新 Map 中的消息列表
            messagesMap.value.set(activeKey.value, currentMessages)
          }
        } else {
          // 非流式输出，按原逻辑处理
          const idx = currentMessages.findIndex((m) => m.id === aiId)
          if (idx !== -1) {
            currentMessages[idx] = {
              ...currentMessages[idx],
              message: aiReply,
              loading: false,
              scene: scene, // 保持场景信息
            }
          }

          // 更新 Map 中的消息列表
          messagesMap.value.set(activeKey.value, currentMessages)
        }

        // 清空输入内容
        content.value = ''
      } catch (e) {
        // 错误处理
        const idx = currentMessages.findIndex((m) => m.id === aiId)
        if (idx !== -1) {
          // 判断是否是取消请求导致的错误
          const message = e.name === 'CanceledError' ? '您已取消请求。' : 'AI请求失败，请重试'
          currentMessages[idx] = {
            ...currentMessages[idx],
            message,
            loading: false,
            scene: scene, // 保持场景信息
          }
        }
        if (e.name !== 'CanceledError') {
          message.error('AI请求失败')
        }
      } finally {
        requestLoading.value = false
        aiAbortController = null
      }
    }
  }

  const deleteConversationMessages = (key) => {
    messagesMap.value.delete(key)
  }

  const cancelMessage = (isCreatingNewConversation, scene) => {
    console.log('🐯 ~ cancelMessage ~ scene:', scene)
    requestLoading.value = false

    // 如果存在未完成的请求，取消它
    if (aiAbortController) {
      aiAbortController.abort()
      aiAbortController = null
    }

    if (isCreatingNewConversation.value) {
      const idx = tempMessages.value.findIndex((m) => m.role === 'ai' && m.loading)
      if (idx !== -1) {
        tempMessages.value[idx] = {
          ...tempMessages.value[idx],
          message: '您已取消请求。',
          loading: false,
          scene: scene, // 保持场景信息
        }
      }
    } else {
      const currentMessages = getCurrentMessages(activeKey.value)
      const idx = currentMessages.findIndex((m) => m.role === 'ai' && m.loading)
      if (idx !== -1) {
        currentMessages[idx] = {
          ...currentMessages[idx],
          message: '您已取消请求。',
          loading: false,
          scene: scene, // 保持场景信息
        }

        messagesMap.value.set(activeKey.value, currentMessages)
      }
    }
  }

  return {
    messagesMap,
    tempMessages,
    content,
    requestLoading,
    BubbleItems,
    sendMessage,
    cancelMessage,
    deleteConversationMessages,
  }
}
